package com.liang.syn;

/**
 * @Author:liangli
 * @Date:2020/11/21 13:01
 */
//不安全的买票
    //线程不安全有负数 重买
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket by=new BuyTicket();

        new Thread(by,"苦逼的我").start();
        new Thread(by,"牛逼的你").start();
        new Thread(by,"可恶的黄牛党").start();

    }
}

class BuyTicket implements Runnable{

    //票
    private int ticketNums=10;
    private Boolean flag=true;//外部停止方式
    @Override
    public void run() {
        //买票
        while (flag){
            buy();
        }
    }

    //synchronized 同步方法 锁的是this
    public synchronized void buy(){
        //判断是否有票
        if (ticketNums<=0){
            flag=false;
            return;
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到第"+ticketNums--);
    }
}